package com.zzx.schoolfellow.config;


import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;

import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * @program: schoolfeoolw_backend
 * @description: WS
 * @author: zzx
 * @create: 2023-03-26 12:41
 **/
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(chatWebSocketHandler(), "/new-endpoint/{userId}/{targetUserId}");
    }

    @Bean
    public WebSocketHandler chatWebSocketHandler() {
        return new WebSocketHandler();
    }
//
//private List<WebSocketSession> sessionMap = new ArrayList<>();
//
//
//
//    @Override
//    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
//        registry.addHandler(myWebSocketHandler(), "/chat/{senderId}/{receiverId}")
//                .setAllowedOrigins("*")
//                .addInterceptors(new HandshakeInterceptor() {
//                    @Override
//                    public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse,
//                                                   org.springframework.web.socket.WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
//                        String path = serverHttpRequest.getURI().getPath();
//                        String[] segments = path.split("/");
//                        Long senderId = Long.valueOf(segments[2]);
//                        Long receiverId = Long.valueOf(segments[3]);
//                        map.put("senderId", senderId);
//                        map.put("receiverId", receiverId);
//                        return true;
//                    }
//                    @Override
//                    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, org.springframework.web.socket.WebSocketHandler webSocketHandler, Exception e) {
//
//                    }
//                });
//    }
//
//    @Bean
//    @CrossOrigin
//    public WebSocketHandler myWebSocketHandler() {
//        return new WebSocketHandler();
//    }
//private class MyHandler extends TextWebSocketHandler {
//    @Override
//    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
//        Long userId = getUserIdFromSession(session);
//        sessionMap.add(session);
//        broadcast("新用户加入");
//    }
//
//    @Override
//    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
//        Long userId = getUserIdFromSession(session);
//        sessionMap.remove(userId);
//        broadcast("用户离开");
//    }
//
//    @Override
//    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
//        JSONObject json = new JSONObject(message.getPayload());
//        Long senderId = json.getLong("sender");
//        Long receiverId = json.getLong("receiver");
//        String content = json.getString("content");
//
//        WebSocketSession receiverSession = findSessionById(receiverId);
//        if (receiverSession != null && receiverSession.isOpen()) {
//            JSONObject response = new JSONObject();
//            response.put("sender", senderId);
//            response.put("receiver", receiverId);
//            response.put("content", content);
//            response.put("timestamp", System.currentTimeMillis());
//            receiverSession.sendMessage(new TextMessage(response.toString()));
//        }
//    }
//
//    private WebSocketSession findSessionById(Long userId) {
//        for (WebSocketSession session : sessionMap) {
//            Long sessionId = getUserIdFromSession(session);
//            if (sessionId != null && sessionId.equals(userId)) {
//                return session;
//            }
//        }
//        return null;
//    }
//
//    private void broadcast(String message) throws IOException {
//        for (WebSocketSession session : sessionMap) {
//            session.sendMessage(new TextMessage(message));
//        }
//    }
//
//    private Long getUserIdFromSession(WebSocketSession session) {
//        Long userId = (Long) session.getAttributes().get("userId");
//        return userId;
//    }
//}
}
